<?php
namespace Admin\Controller;

use Think\Page;

class AdminuserController extends CommonController
{
    public $model = null;

    public function __construct()
    {
        parent::__construct();
        $this->model = M('admin_user');
    }

    /**
     * 数据列表
     * @return [type]
     */
    public function index()
    {
        $where = [];

        // 查找
        $username = I('get.username', 0, 'trim');
        if ($username) {

            $where['username']  = ['LIKE', '%' . $username . '%'];
            $fields['username'] = $username;
            $this->assign('username', $username);
        }

        $count = $this->model->where($where)->count();
        $this->assign('count', $count);

        $pages = new Page($count, C('PAGE'), $fields);
        $this->assign('pages', $pages->show());

        $datas = $this->model->where($where)->limit($pages->firstRow . ',' . $pages->listRows)->select();
        $this->assign('datas', $datas);

        $this->assign('bread_crumb', $bread_crumb = generate_bread_crumb([
            '权限控制',
            '管理员列表',
        ]));
        $this->display();
    }

    /**
     * 添加数据，添加完修改
     */
    public function add()
    {
        if (IS_GET) {

            $this->assign('group', D('Admin/Html', 'Service')->groupSelect());
            $this->display();

        } elseif (IS_POST) {
            $data = I('post.', []);

            $is_exits = $this->model
                ->where(['username' => $data['username']])
                ->count();
            if ($is_exits) {
                $this->error('帐号已存在');
            }

            if (!$data['username'] || !preg_match("/^[a-zA-Z]{5,20}/", $data['username']) || strlen($data['password']) < 6) {
                $this->error('帐号必须字母开头不少于5位，密码不少于6位');
            };

            // 首字母大写，下划线
            // 如：Ad  Ad_Banner
            $result = upload('Admin_Avatar');

            // 加密处理
            $data['password'] = admin_password($data['password']);
            $data['add_time'] = CUR_DATETIME;
            $id               = $this->model->add($data);

            if ($result && $id) {
                $this->model
                    ->where(['id' => $id])
                    ->save(['avatar' => $result['avatar']['url']]);
            }
            var_dump($data);exit;
            // 更新用户角色
            $this->updateGroup($id, $data['group_id']);

            $this->success('添加成功', U(CONTROLLER_NAME . '/update', [
                'id' => $id,
            ]));
        }
    }

    public function update()
    {
        if (IS_GET) {

            $id = I('get.id', 0, 'intval');

            $data = $this->model->find($id);
            $this->assign('data', $data);

            $group_id = M('admin_group_access')->where(['uid' => $data['id']])->getField('group_id');
            $this->assign('group', D('Admin/Html', 'Service')->groupSelect($group_id));

            $this->display();

        } elseif (IS_POST) {

            $id   = I('post.id', 0, 'intval');
            $data = [
                'password' => I('post.password', '', 'trim'),
                'salt'     => I('post.salt', 0, 'intval'),
                'group_id' => I('post.group_id', 0, 'intval'),
            ];

            if ($data['password'] && !empty($data['password'])) {
                $data['salt']     = rand_number(0, 9999);
                $data['password'] = admin_password($data['password'], $data['salt']);
            }
            // 首字母大写，下划线
            // 如：Ad  Ad_Banner
            $result = upload('Admin_Avatar');

            $this->model->where(['id' => $id])->save($data);

            if (isset($result['image'])) {
                $this->model
                    ->where(['id' => $id])
                    ->save(['avatar' => $result['image']['url']]);
            }

            // 更新用户角色
            $this->updateGroup($id, $data['group_id']);

            $this->success('修改成功', U(CONTROLLER_NAME . '/update', [
                'id' => $id,
            ]));
        }
    }

    /**
     * 删除用户
     * @return [type] [description]
     */
    public function delete()
    {
        $id = I('post.id');
        if (in_array($id, C('AUTH_CONFIG.AUTH_SUPER'))) {
            error(1001, '超级管理员不能删除');
        }

        $is = $this->model->delete($id);

        if ($is) {
            success([
                'id' => $id,
            ]);
        } else {
            error(1008, '删除失败');
        }
    }

    /**
     * 更新用户角色
     * @param  [type] $id       [description]
     * @param  [type] $group_id [description]
     * @return [type]           [description]
     */
    private function updateGroup($id, $group_id)
    {
        $is_exits = M('admin_group_access')
            ->where(['uid' => $id])
            ->count();

        if ($is_exits) {

            return M('admin_group_access')->where(['uid' => $id])->save(['group_id' => $group_id]);

        } else {

            $group_access = [
                'uid'      => $id,
                'group_id' => $group_id,
            ];
            return M('admin_group_access')->add($group_access);
        }

    }
}
